/*
 * @Description: 库管理列表
 * @Author: Zzt
 * @Date: 2022-10-27 15:36:29
 * @LastEditTime: 2022-11-27 16:25:25
 */

import { useEffect, useMemo, useState } from 'react';
import { Button, Space, Table } from 'antd';
import { useReportTemplateContext } from '../contexts/ReportTemplateContext';
import EditReport from './dialogs/EditReport';
import { isNullObj } from '@/utils';
import { reportPreview } from '@/api/report';
import type { ColumnsType } from 'antd/es/table';

const PageList = () => {
  const {
    reportList,
    getReportTempList,
    setSelectKey,
    selectItems,
    selectLevel,
    openDesign,
    openPreview,
    typeFilter
  } = useReportTemplateContext();
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState({});
  const [editReportVisible, setEditReportVisible] = useState(false);
  const [listQuery, setListQuery] = useState({
    pageNo: 1,
    pageSize: 10,
    param: {}
  });
  const [total, setTotal] = useState(0);

  useEffect(() => {
    if (selectLevel) {
      const { atCode, atType, level } = selectLevel;
      setListQuery((state) => ({
        ...state,
        param: { atCode, atType, level }
      }));
    }
  }, [selectLevel]);

  /* 切换页码查找列表 */
  useEffect(() => {
    if (listQuery && !isNullObj(listQuery.param)) {
      setLoading(true);
      getReportTempList(listQuery)
        .then((res: any) => {
          setTotal(res?.totalCount);
        })
        .finally(() => {
          setLoading(false);
        });
    }
  }, [listQuery]);

  /**
   * @description 切换页码触发
   * @param {number} page 页码
   * @param {number} pageSize 每页条目数
   */
  const pageChange = (page: number, pageSize: number) => {
    setListQuery((state) => ({
      ...state,
      pageNo: page,
      pageSize
    }));
  };
  /**
   * @description : 表格选项相关设置
   * @param {number} selectedRowKeys 选择的项目的KEY
   */
  const onSelectChange = (selectedRowKeys: number[]) => {
    setSelectKey(selectedRowKeys);
  };
  /**
   * @description:  表格多选配置
   */
  const rowSelection = {
    selectItems,
    onChange: onSelectChange
  };

  const onEdit = (record: any) => {
    setData(record);
    setEditReportVisible(true);
  };

  const openPreviewFlow = (id: number) => {
    reportPreview(id).then((res) => {
      const blob = res.data;
      // const objUrl = URL.createObjectURL(blob);
      const binaryData = [];
      binaryData.push(blob);
      const objUrl = window.URL.createObjectURL(new Blob(binaryData, { type: 'application/pdf' }));

      // window.open(`http://192.168.0.200:8888/pdf/pdfjs/web/viewer.html?file=${objUrl}`);
      console.log({ objUrl });
      window.open(objUrl);
    });
  };

  const columns: ColumnsType = [
    { title: '序号', dataIndex: 'id', key: 'id' },
    { title: '标题', dataIndex: 'name', key: 'name', align: 'center' },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      align: 'center',
      render: (text: string) => typeFilter(parseInt(text, 10))
    },
    // {
    //   title: '数据映射关系',
    //   dataIndex: 'dataMapping',
    //   key: 'type',
    //   align: 'center',
    //   render: (text: string) => dataMappingFilter(parseInt(text, 10))
    // },
    { title: '说明', dataIndex: 'remark', key: 'remark', align: 'center' },
    { title: '创建日期', dataIndex: 'creatTime', key: 'creatTime', align: 'center' },
    { title: '最后修改日期', dataIndex: 'lastChange', key: 'lastChange', align: 'center' },
    {
      title: '操作',
      key: 'action',
      align: 'center',
      render: (_text, record: any) => (
        <Space>
          <Button type="link" size="small" onClick={() => onEdit(record)}>
            修改
          </Button>
        </Space>
      )
    },
    {
      title: '报表设计',
      key: 'design',
      align: 'center',
      render: (_text, record: any) => (
        <Space>
          <Button
            type="link"
            size="small"
            onClick={() => {
              openPreview(record.id);
            }}
          >
            预览
          </Button>
          {/* <Button */}
          {/*  type="link" */}
          {/*  size="small" */}
          {/*  onClick={() => { */}
          {/*    openPreviewFlow(record.id); */}
          {/*  }} */}
          {/* > */}
          {/*  预览（流） */}
          {/* </Button> */}
          <Button
            type="link"
            size="small"
            onClick={() => {
              openDesign(record.id);
            }}
          >
            设计报表
          </Button>
        </Space>
      )
    }
  ];

  return (
    <>
      <Table
        columns={columns}
        dataSource={reportList}
        loading={loading}
        rowKey="id"
        size="small"
        scroll={{ x: 'max-content' }}
        bordered
        rowSelection={rowSelection}
        pagination={{
          current: listQuery.pageNo,
          pageSize: listQuery.pageSize,
          total,
          onChange: pageChange
        }}
      />

      {useMemo(
        () => (
          <EditReport
            visible={editReportVisible}
            onClose={() => {
              setEditReportVisible(false);
            }}
            data={data}
          />
        ),
        [editReportVisible]
      )}
    </>
  );
};
export default PageList;
